﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Forms;
using AnjLab.SyncIT.App.Properties;
using AnjLab.SyncIT.Core;
using AnjLab.SyncIT.Core.Api;
using MessageBox=System.Windows.MessageBox;

namespace AnjLab.SyncIT.App
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        readonly Timer _timer = new Timer();

        public MainWindow()
        {
            InitializeComponent();
            _timer.Interval = 500;
            _timer.Tick += timer_Tick;
            Loaded += MainWindow_Loaded;
            Closed += MainWindow_Closed;
            NotifyAboutSyncCheckBox.IsChecked = Settings.Default.NotifyAboutSyncResults;
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            _timer.Stop();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (SyncProcess.Instance.InProgress) {
                _syncAllNowButton.IsEnabled = false;
                _syncAllNowLabel.Content = "Syncronizing...";
                _progressBar.Value = SyncProcess.Instance.Progress;
                _progressBar.Visibility = System.Windows.Visibility.Visible;
            } else {
                _progressBar.Visibility = System.Windows.Visibility.Collapsed;
                _syncAllNowLabel.Content = "Sync All Now";
                if (_syncAllNowButton.IsEnabled == false) {
                    _syncSources.ItemsSource = new List<Source>();
                    _syncSources.ItemsSource = Settings.Default.SyncSources;
                }
                _syncAllNowButton.IsEnabled = true;
            }
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            StartWithWindowsCheckBox.IsChecked = App.IsAddedToAutostart();
            _timer.Start();
            _syncIntervalSlider.Value = Settings.Default.SyncIntervalInMinutes;
            
            _syncSources.ItemsSource = Settings.Default.SyncSources;
        }

        private void EditItem_Click(object sender, RoutedEventArgs e)
        {
            var source = _syncSources.SelectedItem as Source;
            if (source == null)
                return;
            var newSource = source.Clone() as Source;
            var window = new EditSourceWindow { Owner = this, Source = newSource };
            if (window.ShowDialog() == true && newSource != null)
            {
                source.OutlookCategory = newSource.OutlookCategory;
                source.OutlookPrefix = newSource.OutlookPrefix;
                source.OutlookDestination = newSource.OutlookDestination;
                source.Paused = newSource.Paused;
                source.SyncTimestamp = newSource.SyncTimestamp;
                source.UserName = newSource.UserName;
                source.SetPassword(newSource.GetPassword());
                source.ProjectBase = newSource.ProjectBase;
                source.CustomizeBody = newSource.CustomizeBody;
                source.BodyTemplate = newSource.BodyTemplate;
                source.CustomizeSubject = newSource.CustomizeSubject;
                source.SubjectTemplate = newSource.SubjectTemplate;
                Settings.Default.Save();
                _syncSources.ItemsSource = new List<Source>();
                _syncSources.ItemsSource = Settings.Default.SyncSources;
            }
        }
        
        private void NewSourceButton_Click(object sender, RoutedEventArgs e)
        {
            sourcesPopup.IsOpen = true;
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var interval = new TimeSpan(0, (int) e.NewValue, 0);
            Settings.Default.SyncIntervalInMinutes = (int) interval.TotalMinutes;
            Settings.Default.Save();
            
            if (App.SyncTimer.Interval != interval.TotalMilliseconds) {
                App.SyncTimer.Stop();
                var ticks = (int)interval.TotalMilliseconds;
                if (ticks > 0) {
                    App.SyncTimer.Interval = ticks;
                    App.SyncTimer.Start();
                }
            }
            _syncIntervalLabel.Content = Library.HumanizeSyncInterval(interval);
        }

        private void DeleteItem_Click(object sender, RoutedEventArgs e)
        {
            var source = _syncSources.SelectedItem as Source;
            if (source != null)
                Settings.Default.SyncSources.Remove(source);
            Settings.Default.Save();
            _syncSources.ItemsSource = new List<Source>();
            _syncSources.ItemsSource = Settings.Default.SyncSources;
        }


        private void SyncAllNow_Click(object sender, RoutedEventArgs e) {
            SyncProcess.Instance.Start(Settings.Default.SyncSources);
        }

        private void pauseMenutItem_Click(object sender, RoutedEventArgs e)
        {
            var source = _syncSources.SelectedItem as Source;
            if (source == null)
                return;
            source.Paused = true;
        }

        private void resumeMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var source = _syncSources.SelectedItem as Source;
            if (source == null)
                return;
            source.Paused = false;
        }

        private void pauseAllMenutItem_Click(object sender, RoutedEventArgs e) {
            App.PauseAll();
        }

        private void resumeAllMenuItem_Click(object sender, RoutedEventArgs e) {
            App.ResumeAll();
        }

        private void GoToMyTasksMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var source = _syncSources.SelectedItem as Source;
            if (source == null)
                return;
            try
            {
                App.StartBrowser(source.GetMyTasksUrl());
            }
            catch (NotImplementedException)
            {
                MessageBox.Show("This function is not implemented!", "Warning", MessageBoxButton.OK,
                                MessageBoxImage.Exclamation);
            }
        }

        private void GoToActiveTasksMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var source = _syncSources.SelectedItem as Source;
            if (source == null)
                return;
            try
            {
                App.StartBrowser(source.GetActiveTasksUrl());
            }
            catch (NotImplementedException)
            {
                MessageBox.Show("This function is not implemented!", "Warning", MessageBoxButton.OK,
                                MessageBoxImage.Exclamation);
            }
        }

        private void StartWithWindowsCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (StartWithWindowsCheckBox.IsChecked == true) {
                App.AddToStartup();
            }
            else {
                App.RemoveFromStartup();
            }
        }

        private void NewTracSourceButton_Click(object sender, RoutedEventArgs e)
        {
            var source = new Source {SyncTimestamp = DateTime.Now.AddDays(-7), ProviderKey = "trac"};
            AddNewSource(source);
        }

        private void NewGoogleSourceCodeButton_Click(object sender, RoutedEventArgs e)
        {
            var source = new Source {SyncTimestamp = DateTime.Now.AddDays(-7), ProviderKey = "googlecode"};
            AddNewSource(source);
        }

        private void NewDotProjectSourceButton_Click(object sender, RoutedEventArgs e)
        {
            var source = new Source { SyncTimestamp = DateTime.Now.AddDays(-7), ProviderKey = "dotProject" };
            AddNewSource(source);
        }

        private void New1CEnterpriseSourceButton_Click(object sender, RoutedEventArgs e)
        {
            var source = new Source { SyncTimestamp = DateTime.Now.AddDays(-7), ProviderKey = "1C:Enterprise" };
            AddNewSource(source);
        }

        private void AddNewSource(Source source) {
            source.BodyTemplate = source.GetProvider().DefaultOutlookItemBodyTemplate;
            var window = new EditSourceWindow
                         {
                             Owner = this,
                             Source = source
                         };
            if (window.ShowDialog() != true)
                return;
            Settings.Default.SyncSources.Add(window.Source);
            Settings.Default.Save();
            _syncSources.ItemsSource = new List<Source>();
            _syncSources.ItemsSource = Settings.Default.SyncSources;
        }

        private void AboutButton_Click(object sender, RoutedEventArgs e)
        {
            AboutWindow.ShowSingle(this);
        }

        private void NotifyAboutSyncCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            Settings.Default.NotifyAboutSyncResults = true;
            Settings.Default.Save();
        }

        private void NotifyAboutSyncCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            Settings.Default.NotifyAboutSyncResults = false;
            Settings.Default.Save();
        }
    }
}